package org.liushengpei.com.intercept;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import org.liushengpei.com.util.result.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import static org.liushengpei.com.constant.RedisConstant.*;

/**
 * 登录拦截器
 */
public class LoginIntercept implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public LoginIntercept(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 请求前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            resultJSON(response);
            return false;
        }
        //解析token,获取用户
        final JWT jwt;
        try {
            jwt = JWTUtil.parseToken(token);
        } catch (Exception e) {
            resultJSON(response);
            return false;
        }
        Object data = jwt.getPayload(TOKEN_USER_INFO);
        if (data == null) {
            resultJSON(response);
            return false;
        }
        String userId = String.valueOf(data);
        if (userId == null || "".equals(userId)) {
            resultJSON(response);
            return false;
        }
        //判断该用户token是否存在或过期
        Boolean isExist = redisTemplate.hasKey(LOGIN_TOKEN + userId);
        //不存在拦截
        if (Boolean.FALSE.equals(isExist)) {
            resultJSON(response);
            return false;
        }
        //判断是否和缓存中的token一致
        String oldToken = redisTemplate.opsForValue().get(LOGIN_TOKEN + userId);
        if (oldToken != null && !oldToken.equals(token)) {
            resultJSON(response);
            return false;
        }
        //刷新该用户key有效期
        redisTemplate.expire(LOGIN_TOKEN + userId, TOKEN_EXPIRE_TIME, TimeUnit.DAYS);
        //刷新用户缓存有效期
        redisTemplate.expire(USER_LOGIN + userId, USER_EXPIRE_TIME, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 拦截后返回结果统一处理
     */
    private void resultJSON(HttpServletResponse response) throws IOException {
        //返回结果编码
        response.setContentType("application/json;charset=UTF-8");
        //给浏览器相应认证失败的数据
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(ResultData.authFail()));
    }
}
